package com.atguigu.aiproject.controller.user;

import com.atguigu.aiproject.entity.ChatMessage;
import com.atguigu.aiproject.entity.ChatSession;
import com.atguigu.aiproject.entity.Result;
import com.atguigu.aiproject.service.ChatService;
import com.atguigu.aiproject.utils.UserContext;
import com.atguigu.aiproject.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/chat")
@Slf4j
public class ChatController {
    @Autowired
    private ChatService chatService;

    /**
     * 获取聊天记录
     *
     * @param userId 当前用户ID
     * @param targetUserId 目标用户ID
     * @param before 查询该时间点之前的消息（可选，默认为当前时间）
     * @param limit 返回消息数量（可选，默认20，最大100）
     * @return 分页的聊天记录
     */
    @GetMapping("/history")
    public Result<PageResult<ChatMessage>> getChatHistory(
            @RequestParam(value = "userId") Integer userId,
            @RequestParam(value = "targetUserId") Integer targetUserId,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime before,
            @RequestParam(required = false) Integer limit) {

        log.info("获取聊天记录: 用户 {} 与 {}, before: {}, limit: {}",
                userId, targetUserId, before, limit);
        try {
            return Result.success(chatService.getChatHistory(userId, targetUserId, before, limit));
        } catch (NumberFormatException e) {
            return Result.error("用户ID参数格式错误");
        } catch (Exception e) {
            return Result.error("获取聊天记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取最近的聊天记录（简化牛魔
     */
    @GetMapping("/history/recent")
    public Result<PageResult<ChatMessage>> getRecentChatHistory(
            @RequestParam Integer userId,
            @RequestParam Integer targetUserId,
            @RequestParam(defaultValue = "20") Integer limit
    ) {

        log.info("获取最近聊天记录: 用户 {} 与 {}", userId, targetUserId);
        try {
            // 当前时间之前的消息
            return Result.success(chatService.getChatHistory(userId, targetUserId, LocalDateTime.now(), limit));
        } catch (NumberFormatException e) {
            return Result.error("用户ID参数格式错误");
        } catch (Exception e) {
            return Result.error("获取聊天记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取更多历史消息（基于搜索ID）
     */
    @GetMapping("/history/more")
    public Result<PageResult<ChatMessage>> getMoreChatHistory(
            @RequestParam String searchId) {

        log.info("获取更多聊天记录，搜索ID: {}", searchId);

        // 解析搜索ID获取参数
        // 格式: chat_{userId}_{targetUserId}_{timestamp}_{limit}
        String[] parts = searchId.split("_");
        if (parts.length < 5) {
            return Result.error("无效的搜索ID格式");
        }

        try {
            Integer userId = Integer.parseInt(parts[1]);
            Integer targetUserId = Integer.parseInt(parts[2]);
            LocalDateTime before = LocalDateTime.parse(parts[3],
                    java.time.format.DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            Integer limit = Integer.parseInt(parts[4]);

            return Result.success(chatService.getChatHistory(userId, targetUserId, before, limit));
        } catch (NumberFormatException e) {
            return Result.error("搜索ID中的参数格式错误: " + e.getMessage());
        } catch (Exception e) {
            return Result.error("搜索ID解析失败: " + e.getMessage());
        }
    }
    
    // 获取会话列表
    @GetMapping("/sessions")
    public Result<List<ChatSession>> getChatSessions() {
        try {
            int currentUserId = UserContext.getUserId();
            List<ChatSession> sessions = chatService.getUserSessions(currentUserId);
            return Result.success(sessions);
        } catch (Exception e) {
            return Result.error("获取会话列表失败: " + e.getMessage());
        }
    }
}